<?php

namespace app\admin\model\scanwork;

use think\Model;

/**
 * 物料模型
 */
class Material extends Model
{
    // 表名
    protected $name = 'scanwork_material';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'stock_status_text'
    ];
    
    /**
     * 状态列表
     */
    public function getStatusList()
    {
        return ['0' => __('停用'), '1' => __('在用')];
    }

    /**
     * 状态文本
     */
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 物料分类列表
     */
    public function getCategoryList()
    {
        return [
            '面料' => __('面料'),
            '辅料' => __('辅料'),
            '五金件' => __('五金件'),
            '填充物' => __('填充物'),
            '包装材料' => __('包装材料'),
            '其他' => __('其他')
        ];
    }

    /**
     * 关联物料分类
     */
    public function category()
    {
        return $this->belongsTo('MaterialCategory', 'category_id', 'id');
    }

    /**
     * 单位列表
     */
    public function getUnitList()
    {
        return [
            'PCS' => __('件'),
            '米' => __('米'),
            '个' => __('个'),
            '公斤' => __('公斤'),
            '平方米' => __('平方米'),
            '卷' => __('卷'),
            '套' => __('套'),
            '条' => __('条')
        ];
    }

    /**
     * 库存状态文本
     */
    public function getStockStatusTextAttr($value, $data)
    {
        $stock = isset($data['stock']) ? $data['stock'] : 0;
        $minStock = isset($data['min_stock']) ? $data['min_stock'] : 0;
        $safetyStock = isset($data['safety_stock']) ? $data['safety_stock'] : 0;
        
        if ($stock <= 0) {
            return '<span class="label label-danger">缺货</span>';
        } elseif ($stock < $minStock) {
            return '<span class="label label-warning">库存不足</span>';
        } elseif ($stock < $safetyStock) {
            return '<span class="label label-info">低于安全库存</span>';
        } else {
            return '<span class="label label-success">正常</span>';
        }
    }

    /**
     * 关联默认供应商
     */
    public function defaultSupplier()
    {
        return $this->belongsTo('Supplier', 'default_supplier_id', 'id');
    }

    /**
     * 关联物料供应商报价
     */
    public function suppliers()
    {
        return $this->hasMany('MaterialSupplier', 'material_id', 'id');
    }

    /**
     * 关联工序物料
     */
    public function processMaterials()
    {
        return $this->hasMany('ProcessMaterial', 'material_id', 'id');
    }

    /**
     * 关联订单物料需求
     */
    public function orderMaterials()
    {
        return $this->hasMany('OrderMaterial', 'material_id', 'id');
    }

    /**
     * 关联采购记录
     */
    public function purchaseRecords()
    {
        return $this->hasMany('PurchaseRecord', 'material_id', 'id');
    }

    /**
     * 获取最优供应商价格
     */
    public function getBestPriceAttr($value, $data)
    {
        $bestSupplier = $this->suppliers()
            ->where('status', 1)
            ->where('is_preferred', 1)
            ->order('price', 'asc')
            ->find();
        
        return $bestSupplier ? $bestSupplier->price : (isset($data['current_price']) ? $data['current_price'] : 0);
    }

    /**
     * 更新当前价格（从最优供应商获取）
     */
    public function updateCurrentPrice()
    {
        $bestSupplier = $this->suppliers()
            ->where('status', 1)
            ->where('is_preferred', 1)
            ->order('price', 'asc')
            ->find();
        
        if ($bestSupplier) {
            $this->save(['current_price' => $bestSupplier->price]);
        }
    }
}

